import { defineComponent, ref, h } from 'vue'
import {
  DataTableColumns,
  FormInst,
  NButton,
  NCard,
  NDataTable,
  NDescriptions,
  NDescriptionsItem,
  NDivider,
  NForm,
  NFormItem,
  NPagination,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui'
import { useRouter } from 'vue-router'
// @ts-ignore
import createRuleGroup from '@/views/integration/monitor/createRuleGroup'
import {
  deleteRuleGroupData,
  getRuleGroup,
  getRuleListData,
  manualTrigger
} from '@/service/modules/integration-monitor'
import styles from '@/views/integration/monitor/index.module.scss'
import createRule from '@/views/integration/monitor/createRule'
import { PartitionDef } from '@/service/modules/integration-monitor/types'
import editRule from '@/views/integration/monitor/editRule'

const infoRuleDefine = defineComponent({
  name: 'infoRuleDefine',
  components: {
    createRuleGroup,
    createRule,
    editRule
  },
  setup() {
    const router = useRouter()

    const tableName = ref(router.currentRoute.value.query.tableName)
    const schemaName = ref(router.currentRoute.value.query.schemaName)

    const createRuleGroupClick = function () {
      showRuleGroupModal.value = true
    }
    const createRuleClick = function () {
      if (!ruleGroupSearchForm.value.id) {
        message.error('请选择规则组')
      } else {
        showCreateRuleModal.value = true
      }
    }

    const showRuleGroupModal = ref(false)
    const showCreateRuleModal = ref(false)
    const showEditRuleModal = ref(false)

    const handleRuleGroupModal = function () {
      showRuleGroupModal.value = false
    }

    const handleCreateRuleModal = function () {
      showCreateRuleModal.value = false
    }

    const handleEditRuleModal = function () {
      showEditRuleModal.value = false
    }

    const ruleGroupList = ref([])

    const getRuleGroupListData = function () {
      // @ts-ignore
      getRuleGroup(tableName.value, schemaName.value)
        .then((res: any) => {
          ruleGroupList.value = res.data
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }

    getRuleGroupListData()

    const message = useMessage()

    type RowData = {
      id: number | string
      name: number | string
      analyseType: number | string
      ruleLevel: number | string
      basePartitionDef: PartitionDef
      checkPartitionDef: PartitionDef
      fieldsName: number | string
      calculateType: number | string
      fixedCompareWay: number | string
      fixedValue: number | string
      swingUpper: number | string
      swingLower: number | string
    }

    const createColumns = ({
      editRuleClick
    }: {
      editRuleClick: (rowData: RowData) => void
    }): DataTableColumns<RowData> => {
      return [
        { title: 'ID', key: 'id' },
        { title: '名称', key: 'name' },
        { title: '分析类型', key: 'analyseType' },
        { title: '规则级别', key: 'ruleLevel' },
        {
          title: '基准分区表达式',
          key: 'basePartitionDef',
          render(row: any) {
            return JSON.stringify(row.basePartitionDef)
          }
        },
        { title: '受检分区表达式', key: 'checkPartitionDef' },
        { title: '字段名称', key: 'fieldsName' },
        { title: '计算类型', key: 'calculateType' },
        { title: '固定值比较规则', key: 'fixedCompareWay' },
        { title: '固定值', key: 'fixedValue' },
        { title: '波动上限', key: 'swingUpper' },
        { title: '波动下限', key: 'swingLower' },
        {
          title: '操作',
          key: 'actions',
          render(row: any) {
            return h(
              NButton,
              {
                size: 'small',
                onClick: () => editRuleClick(row)
              },
              { default: () => '编辑' }
            )
          }
        }
      ]
    }

    const ruleList = ref([])

    const pagination = ref({
      pageSize: 10,
      pageCount: 0,
      page: 1,
      showQuickJumper: true,
      pageSizes: [10, 30, 50],
      showSizePicker: true,
      loading: false,
      onUpdatePage: (page: number) => {
        pagination.value.page = page
      },
      onUpdatePageSize: (pageSize: number) => {
        pagination.value.pageSize = pageSize
        pagination.value.page = 1
      }
    })

    const getRuleList = function (id: number | string) {
      pagination.value.loading = true
      getRuleListData(id)
        .then((res: any) => {
          ruleList.value = res.data
          pagination.value.loading = false
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
          pagination.value.loading = false
        })
    }

    const deleteRuleGroup = function () {
      if (!ruleGroupSearchForm.value.id) {
        message.error('请选择规则组')
      } else {
        // @ts-ignore
        deleteRuleGroupData(ruleGroupSearchForm.value.id)
          .then((res: any) => {
            message.success(res.msg ? res.msg : '删除成功')
            getRuleGroupListData()
          })
          .catch((err: any) => {
            message.error(err.msg ? err.msg : '接口未知错误')
          })
      }
    }

    const ruleGroupSearchForm = ref({
      id: undefined
    })

    const rules = ref({
      id: { required: false, message: '请选择规则组', trigger: 'blur' }
    })

    const searchSubmit = function () {
      if (!ruleGroupSearchForm.value.id) {
        message.error('请选择规则组')
      } else {
        // @ts-ignore
        getRuleList(ruleGroupSearchForm.value.id)
      }
    }

    const formRef = ref<FormInst | null>(null)

    const manualTriggerClick = function () {
      if (!ruleGroupSearchForm.value.id) {
        message.error('请选择规则组')
      } else {
        // @ts-ignore
        manualTrigger(ruleGroupSearchForm.value.id)
          .then((res: any) => {
            message.success(res.msg ? res.msg : '触发成功')
          })
          .catch((err: any) => {
            message.error(err.msg ? err.msg : '接口未知错误')
          })
      }
    }

    const ruleItemData = ref({})

    return {
      router,
      tableName,
      schemaName,
      createRuleGroupClick,
      createRuleClick,
      handleRuleGroupModal,
      handleCreateRuleModal,
      handleEditRuleModal,
      showRuleGroupModal,
      showCreateRuleModal,
      showEditRuleModal,
      getRuleGroupListData,
      ruleGroupList,
      message,
      columns: createColumns({
        editRuleClick(rowData) {
          message.info('send mail to ' + rowData.name)
          ruleItemData.value = rowData
          showEditRuleModal.value = true
        }
      }),
      ruleList,
      pagination,
      getRuleList,
      deleteRuleGroup,
      ruleGroupSearchForm,
      rules,
      searchSubmit,
      formRef,
      manualTriggerClick,
      ruleItemData
    }
  },
  render() {
    return (
      <NCard>
        <NDescriptions>
          <NDescriptionsItem label='库名'>{this.tableName}</NDescriptionsItem>
          <NDescriptionsItem label='表名'>{this.schemaName}</NDescriptionsItem>
        </NDescriptions>
        <NDivider></NDivider>
        <NSpace vertical>
          <NForm
            inline
            labelPlacement={'left'}
            model={this.ruleGroupSearchForm}
            size={'medium'}
            ref={'formRef'}
          >
            <NFormItem path='id' label='规则组'>
              <NSelect
                labelField={'name'}
                class={styles['form-item']}
                valueField={'id'}
                v-model:value={this.ruleGroupSearchForm.id}
                options={this.ruleGroupList}
                placeholder={'请选择规则组'}
                clearable
              ></NSelect>
            </NFormItem>
            <NSpace>
              <NButton type={'primary'} onClick={this.searchSubmit}>
                搜索
              </NButton>
              <NButton type={'primary'} onClick={this.createRuleGroupClick}>
                新建规则组
              </NButton>
              <NButton
                type={'warning'}
                // @ts-ignore
                onClick={this.deleteRuleGroup}
              >
                删除规则组
              </NButton>
              <NButton type={'error'} onClick={this.manualTriggerClick}>
                手动触发
              </NButton>
            </NSpace>
          </NForm>
          <NSpace vertical>
            <NSpace>
              <NButton type={'primary'} onClick={this.createRuleClick}>
                新建规则
              </NButton>
            </NSpace>
            <NDataTable
              columns={this.columns}
              data={this.ruleList}
              loading={this.pagination.loading}
            ></NDataTable>
            <NPagination
              class={styles['page-position']}
              display-order={['quick-jumper', 'pages', 'size-picker']}
              page-count={this.pagination.pageCount}
              page-size={this.pagination.pageSize}
              page-sizes={this.pagination.pageSizes}
              page={this.pagination.page}
              on-update:page={this.pagination.onUpdatePage}
              on-update:page-size={this.pagination.onUpdatePageSize}
              show-quick-jumper
              show-size-picker
            ></NPagination>
          </NSpace>
        </NSpace>
        <createRuleGroup
          propModal={this.showRuleGroupModal}
          onCloseModal={this.handleRuleGroupModal}
          onUpdateRuleGroup={this.getRuleGroupListData}
          close-modal={this.handleRuleGroupModal}
        ></createRuleGroup>
        <createRule
          propModal={this.showCreateRuleModal}
          onCloseModal={this.handleCreateRuleModal}
          onUpdateRule={this.getRuleList}
          close-modal={this.handleCreateRuleModal}
        ></createRule>
        <editRule
          propModal={this.showEditRuleModal}
          ruleItem={this.ruleItemData}
          onCloseModal={this.handleEditRuleModal}
          onUpdateRule={this.getRuleList}
          close-modal={this.handleEditRuleModal}
        ></editRule>
      </NCard>
    )
  }
})

export default infoRuleDefine
